import { css } from "@emotion/css";
import {
  Breadcrumb,
  Button,
  Form,
  Input,
  Message,
  Popconfirm,
  Space,
  Table,
  Tooltip,
} from "@arco-design/web-react";
import { usePagination } from "../../hooks/usePagination.ts";
import { Link } from "../../components/Link";
import { useAPI } from "../../hooks/useAPI.ts";
import { useQuery } from "react-query";
// import { CallBuildingAdminModal } from "../../components/CallBuildingAdminModal";
import { useState } from "react";
import {
  IconDelete,
  IconEdit,
  IconPlusCircle,
  IconRefresh,
  IconRight,
} from "@arco-design/web-react/icon";
import { BuildingDataRow } from "../../api/types/building.tsx";
import { useAsyncFn, useDebounce } from "react-use";
import { SystemUserInfoData } from "../../api/types/system-user-info.ts";
import { useNavigate } from "react-router-dom";

export default function Building() {
  const api = useAPI();
  const { pagination, pageNum, pageSize, setTotal, resetPage } =
    usePagination();
  const [formRef] = Form.useForm<BuildingDataRow>();
  const [searchValues, setSearchValues] =
    useState<Partial<BuildingDataRow> | null>(null);
  const { data, isLoading, refetch } = useQuery(
    ["getBuildingList", pageNum, pageSize],
    async () => {
      try {
        const values = searchValues || {};
        const response = await api.getBuildingList({
          pageNum,
          pageSize,
          ...values,
        });
        setTotal(response.data?.data.total || 0);

        return response.data?.data.rows.map((row: any, index: number) => ({
          index: index + 1 + (pageNum - 1) * pageSize, // Add index starting from 1, // Add index starting from 1
          ...row,
        }));
      } catch (error) {
        if (error instanceof Error) {
          Message.error(error.message);
        } else {
          Message.error("操作失败，请稍后重试");
        }
      }
    },
  );

  const navigate = useNavigate();
  const [, onSearch] = useAsyncFn(async (values: Partial<BuildingDataRow>) => {
    resetPage();
    setSearchValues(values);
    await refetch();
  });
  useDebounce(
    () => {
      refetch();
    },
    300,
    [searchValues],
  );
  return (
    <div>
      <Breadcrumb
        className={css`
          padding: 12px;
          border-radius: 1px;
          font-weight: bold;
          border-left: 5px solid rgb(var(--primary-6));
          margin-bottom: 20px;
        `}
        separator={<IconRight />}
      >
        <Breadcrumb.Item style={{ fontWeight: 400 }}>
          <Link
            to="/buildingManagement/index"
            style={{
              textDecoration: "none",
              transition: "color 0.3s",
              fontWeight: "bold",
              fontSize: "15px",
            }}
          >
            楼栋管理
          </Link>
        </Breadcrumb.Item>
      </Breadcrumb>

      <div
        className={css`
          width: 100%;
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
        `}
      >
        <Form form={formRef} layout={"inline"} onSubmit={onSearch}>
          <Form.Item field="key" label="搜索：">
            <Input.Search
              value={searchValues?.key}
              onChange={(v) => setSearchValues({ ...searchValues, key: v })}
              placeholder="请输入关键字"
              style={{ width: "200px" }}
              allowClear
            />
          </Form.Item>
          <Form.Item>
            <Button
              type="outline"
              htmlType="button"
              onClick={() => {
                formRef.resetFields();
                setSearchValues({ ...searchValues, key: "" });
              }}
            >
              <IconRefresh />
              重置
            </Button>
          </Form.Item>
        </Form>
        <Link to={`/buildingManagement/addBuilding`}>
          <Button type="primary" size="small">
            <IconPlusCircle />
            添加楼栋
          </Button>
        </Link>
      </div>

      <Table
        data={data}
        loading={isLoading}
        pagination={pagination}
        showSorterTooltip={false}
        rowKey="index"
        columns={[
          {
            title: "序号",
            dataIndex: "index",
            key: "index",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            sorter: (a, b) => a.index - b.index,
          },
          {
            title: "楼栋号",
            dataIndex: "name",
            key: "name",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
          },
          {
            title: "楼层数",
            dataIndex: "floorCount",
            key: "floorCount",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
          },
          {
            title: "房间总数",
            dataIndex: "roomCount",
            key: "roomCount",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
          },
          {
            title: "楼栋电话",
            dataIndex: "phone",
            key: "phone",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
          },
          {
            title: "生活管家",
            dataIndex: "managers",
            key: "managers",
            ellipsis: true,
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            render: (managers) =>
              managers?.reduce(
                (pre: string, cur: SystemUserInfoData) =>
                  pre
                    ? `${pre}，${cur.nickName} - ${cur.phonenumber}`
                    : `${cur.nickName} - ${cur.phonenumber}`,
                "",
              ) || "无",
          },

          {
            title: "操作",
            dataIndex: "id",
            key: "actions",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            render: (record, row) => (
              <Space>
                <Tooltip content="编辑">
                  <Button
                    size="small"
                    shape="circle"
                    type="outline"
                    icon={<IconEdit />}
                    onClick={(e) => {
                      e.preventDefault();
                      navigate(`/buildingManagement/editBuilding/${record}`);
                    }}
                  />
                </Tooltip>
                <Popconfirm
                  focusLock
                  title="请确认"
                  content={`是否删除该楼栋 ${row.name}？(注:删除楼栋将直接删除绑定楼栋的所有房间信息)`}
                  onOk={async () => {
                    await api.saveBuilding({
                      id: record,
                      del: true,
                    });
                    await refetch();
                  }}
                >
                  <Tooltip content="删除">
                    <Button
                      size="small"
                      shape="circle"
                      type="outline"
                      icon={<IconDelete />}
                    />
                  </Tooltip>
                </Popconfirm>
              </Space>
            ),
          },
        ]}
      />
    </div>
  );
}
